from django.shortcuts import render, HttpResponse, redirect
from django import forms
from django.core.validators import RegexValidator
import re
from web import models
from s28 import settings
from utrl.centent import sms
import random
from django_redis import get_redis_connection
from django.http import JsonResponse
import json
from django.core.exceptions import ValidationError
import io
from scripts.init_price_police import S28
import time
import datetime
from utrl.centent.alipay import AliPay
from django.conf import settings


class BootstragForm(forms.BaseForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.boot_remove = ['color']
        for name, filed in self.fields.items():
            if name in self.boot_remove:
                pass
            else:
                old_class = filed.widget.attrs.get('class', '')

                filed.widget.attrs['class'] = '{} form-control'.format(old_class)



#################################  完善后的代码  ##########################################################################################
# 验证提交的注册信息是否符合要求
# 注册样式和校验
class RegisTerS(forms.Form):
    name = forms.CharField(label='用户名', max_length=32, widget=forms.TextInput(
        attrs={'class': 'form-control'}))
    pwd = forms.CharField(label='密码', widget=forms.PasswordInput(
        attrs={'class': 'form-control'}))

    mobile_phone = forms.CharField(label='手机号', validators=[
        RegexValidator(r'^(1[3|4|5|7|9|8])\d{9}$', '手机格式不正确')],
                                   widget=forms.TextInput(
                                       attrs={'class': 'form-control'}))
    code = forms.CharField(label='验证码', widget=forms.TextInput(
        attrs={'class': 'form-control', 'style': 'width:170px'}))

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if len(name) < 8:
            raise ValidationError('用户名不能小于8位(钩子)')
        else:
            # 取数据库进行校验 看有没有重复的数据
            search_name = models.BOOK().search_user(name)
            if search_name != True:
                raise ValidationError('已经存在了(钩子)')
            else:
                return name

    def clean_pwd(self):
        pwd = self.cleaned_data.get('pwd')
        if len(pwd) < 8:
            raise ValidationError('密码不能小于八位(钩子)')
        else:
            return pwd

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data.get('mobile_phone')
        re_mobile_phone = models.BOOK().search_mobile_phone(mobile_phone)
        if re_mobile_phone != 1:
            raise ValidationError('手机号已经注册了(钩子)')
        else:
            return mobile_phone

    def clean_code(self):
        mobile_phone = self.cleaned_data.get('mobile_phone')
        code = self.cleaned_data.get('code')
        if not mobile_phone:
            raise ValidationError('请输入手机号')
        conn = get_redis_connection()
        search_code = conn.get(mobile_phone)
        if search_code == None:
            raise ValidationError('请先发送验证码(钩子)')

        elif search_code.decode('utf-8') != str(code.strip()):

             raise ValidationError('请输入正确的验证码(钩子)')
        else:
            return code


##################################################################################################
# 验证短信类


class SendSmsForm(forms.Form):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3|4|5|6|7|8|9]\d{9}$', '手机号格式错误')])

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile_phone(self):
        """ 手机号校验的钩子 """
        mobile_phone = self.cleaned_data['mobile_phone']
        print(mobile_phone)
        # 判断短信模板是否有问题
        tpl = self.request.GET.get('tpl')
        print(tpl)
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
        if not template_id:
            # self.add_error('mobile_phone','短信模板错误')
            raise ValidationError('短信模板错误')

        exists = models.BOOK().search_mobile_phone(mobile_phone)  # 没有数据返回1 有数据返回None
        if tpl == 'login':
            if exists == 1:
                raise ValidationError('手机号不存在，您需要注册')
        else:
            # 校验数据库中是否已有手机号
            if exists != 1:
                raise ValidationError('手机号已存在(钩子)')

        code = random.randrange(1000, 9999)

        # 发送短信

        ret_sms = sms.send_sms_single(mobile_phone, template_id, [code, ])
        if ret_sms['result'] != 0:
            raise ValidationError("短信发送失败，{}".format(ret_sms['errmsg']))

        # 验证码 写入redis（django-redis）
        conn = get_redis_connection()
        conn.set(mobile_phone, code, ex=60)

        return mobile_phone


#----------------------  短信登陆--------------------------------

class LoginSmsFrom(forms.Form, BootstragForm):


    mobile_phone = forms.CharField(label='手机号', validators=[
        RegexValidator(r'^(1[3|4|5|7|9|8])\d{9}$', '手机格式不正确')],
                                   widget=forms.TextInput(
                                       attrs={'class': 'form-control'}),required=False)
    code = forms.CharField(label='验证码', widget=forms.TextInput(
        attrs={'class': 'form-control', 'style': 'width:170px'}))
    # mobile_phone = forms.CharField(label='手机号')
    # code = forms.CharField(label='验证码', widget=forms.TextInput())

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']
        exists = models.BOOK().search_mobile_phone(mobile_phone)
        # user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        if exists == 1:
            raise ValidationError('手机号不存在, 请注册')

        return mobile_phone
    def clean_code(self):
        mobile_phone = self.cleaned_data.get('mobile_phone')
        code = self.cleaned_data.get('code')
        conn = get_redis_connection()
        ret = conn.get(mobile_phone)
        if ret == None:
            raise ValidationError('请发送验证码')
        else:
            if ret.decode('utf-8') != str(code):
                raise ValidationError('请输入正确的验证码')
        return code

#  --------------------------  账号登陆-------------------------


class LoginForm(forms.Form, BootstragForm):
    user = forms.CharField(label='用户名',widget=forms.TextInput({'placeholder':'请输入账号',}))
    password = forms.CharField(label='密码', widget=forms.PasswordInput({'placeholder':'请输入密码',}))
    code = forms.CharField(label='验证码')
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_code(self):
        """钩子  图片验证码是否正确"""
        # 读取用户输入的验证码
        code = self.cleaned_data.get('code')
        session_code = self.request.session.get('image_code')
        if not session_code:
            raise ValidationError('验证码过期 请重新获取')
        else:
            if code.upper().strip() != session_code:
                raise ValidationError('验证码错误 请重新输入')
            return code
